<script setup lang="ts">
/**
 * @name UnitManagement
 * @description 单位管理
 */
import {
  Delete,
  Edit,
  Plus,
  Warning,
} from '@element-plus/icons-vue'
import type { Action } from 'element-plus'
import FormModal from './components/FormModal.vue'
import InfoFormModal from './components/InfoFormModal.vue'
import {
  defaultFormData,
  defaultInfoFormData,
} from './index'
import type {
  TableColumn,
  UnitInfo,
  UnitTypeInfo,
} from '@/types'
import { unitManagementApi } from '@/api'
// ------------------use------------------
// #region
const { globalProperties, $confirm, $message }
  = useCurrentInstance()
const { withLoading, spaceLoading, loading }
  = useDefineLoading()
const [tableData, setTableData] = useState<UnitTypeInfo[]>(
  [],
)
const [infoTableData, setInfoTableData] = useState<
  UnitInfo[]
>([])
const [formData, setFormData] = useState<any>({
  ...defaultFormData,
})
const [infoFormData, setInfoFormData] = useState({
  ...defaultInfoFormData,
})
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const [unitClassifyId, setUnitClassifyId] = useState(0)
const [isEdit, setIsEdit] = useState(false)
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<UnitTypeInfo>[] = [
  {
    key: uuid(),
    prop: 'sort',
    width: '120',
    label: '序号',
  },
  {
    key: uuid(),
    label: '名称',
    prop: 'typeName',
  },
]
const columns1: TableColumn<UnitInfo>[] = [
  {
    key: uuid(),
    prop: 'sort',
    width: '120',
    label: '序号',
  },
  {
    key: uuid(),
    label: '中文名',
    prop: 'unitName',
  },
  {
    key: uuid(),
    label: '英文名',
    prop: 'unitExpression',
  },
]
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const modalRef = ref<InstanceType<typeof FormModal>>()
const infoModalRef
  = ref<InstanceType<typeof InfoFormModal>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
// #endregion
// ------------------生命周期------------------
// #region
onMounted(() => {
  getTableData()
})
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
async function deleteData(id: number) {
  const res: Action = await $confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  await unitManagementApi.deleteUnitTypeById(id)
  globalProperties.$message.success('单位类别删除成功！')
  getTableData()
}
async function deleteInfoData(id: number) {
  const res: Action = await $confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  await unitManagementApi.deleteUnitById(id)
  globalProperties.$message.success('单位信息删除成功！')
  getInfoTableData()
}
async function showEditDialog(row: UnitTypeInfo) {
  setIsEdit(true)
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('编辑单位分类')
  setFormData({ ...defaultFormData, ...row })
}
async function showAddDialog() {
  setIsEdit(false)
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('新增单位分类')
  setFormData({ ...defaultFormData })
}
async function showInfoEditDialog(row: UnitInfo) {
  setIsEdit(true)
  infoModalRef.value?.open()
  await nextTick()
  setFormModalTitle('编辑单位信息')
  setInfoFormData({ ...defaultInfoFormData, ...row })
}
async function showInfoAddDialog() {
  setIsEdit(false)
  infoModalRef.value?.open()
  await nextTick()
  setFormModalTitle('新增单位信息')
  setInfoFormData({
    ...defaultInfoFormData,
    typeId: unitClassifyId.value,
  })
}
async function getTableData() {
  const { data: res } = await withLoading(
    unitManagementApi.selectUnitTypeList,
  )()
  setTableData(res)
  // console.log(tableData.value);

  if (res.length !== 0) {
    setUnitClassifyId(res[0]!.id)
    getInfoTableData()
  }
}
async function getInfoTableData() {
  const { data: res } = await withLoading(
    unitManagementApi.selectUnitListByTypeId,
  )(unitClassifyId.value)
  if (res.length === 0) {
    setInfoTableData([])
    return
  }

  setInfoTableData(res)
}
function success() {
  getTableData()
  modalRef.value?.close()
  $message.success('保存成功！')
}
function infoSuccess() {
  getInfoTableData()
  infoModalRef.value?.close()
  $message.success('保存成功！')
}

function tableRowClassName({ row }: any) {
  if (row.id === unitClassifyId.value) {
    return 'table-highlight'
  }

  return ''
}
function handleRowClick(row: any) {
  setUnitClassifyId(row.id)
  getInfoTableData()
}
// #endregion
</script>

<template>
  <div class="padding-sm flex gap-col-sm container">
    <div
      class="flex-direction height-fill overflow width-2/5 flex align-end"
    >
      <view-table
        :loading="spaceLoading.default"
        :columns="columns"
        :data="tableData"
        :row-class-name="tableRowClassName"
        border
        :show-toolbox="false"
        @row-click="handleRowClick"
      >
        <template #actions>
          <div class="align-center flex">
            <h5 class="margin-0 margin-right-sm">
              计量单位分类
            </h5>
            <el-button
              type="primary"
              :icon="Plus"
              @click="showAddDialog"
            >
              新增
            </el-button>
          </div>
        </template>
        <template #indexHeader>
          <span class="align-center flex justify-center">
            序号
            <el-tooltip
              content="数值越小排序等级越高"
              placement="top"
            >
              <el-icon
                class="c-pointer margin-left-xs text-orange"
              >
                <Warning />
              </el-icon>
            </el-tooltip>
          </span>
        </template>
        <template #operate="{ row }">
          <TdButton
            title="编辑"
            :icon="Edit"
            type="primary"
            @click="showEditDialog(row)"
          />
          <TdButton
            title="删除"
            :icon="Delete"
            type="danger"
            @click="deleteData(row.id)"
          />
        </template>
      </view-table>
    </div>
    <div
      class="flex-direction height-fill width-3/5 overflow flex align-end"
    >
      <view-table
        :loading="loading"
        :columns="columns1"
        :data="infoTableData"
        border
        :show-toolbox="false"
      >
        <template #indexHeader>
          <span class="align-center flex justify-center">
            序号
            <el-tooltip
              content="数值越小排序等级越高"
              placement="top"
            >
              <el-icon
                class="c-pointer margin-left-xs text-orange"
              >
                <Warning />
              </el-icon>
            </el-tooltip>
          </span>
        </template>
        <template #actions>
          <div class="align-center flex">
            <h5 class="margin-0 margin-right-sm">
              计量单位信息
            </h5>
            <el-button
              type="primary"
              :icon="Plus"
              :disabled="!unitClassifyId"
              @click="showInfoAddDialog"
            >
              新增
            </el-button>
          </div>
        </template>
        <template #operate="{ row }">
          <TdButton
            title="编辑"
            :icon="Edit"
            type="primary"
            @click="showInfoEditDialog(row)"
          />
          <TdButton
            title="删除"
            :icon="Delete"
            type="danger"
            @click="deleteInfoData(row.id)"
          />
        </template>
      </view-table>
    </div>

    <FormModal
      ref="modalRef"
      v-model:data="formData"
      :is-edit="isEdit"
      :title="formModalTitle"
      @success="success"
    />
    <InfoFormModal
      ref="infoModalRef"
      v-model:data="infoFormData"
      :title="formModalTitle"
      @success="infoSuccess"
    />
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
